package com.yix.admin.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.yix.admin.modules.security.service.UserCacheClean;
import com.yix.admin.modules.system.entity.SysMenu;
import com.yix.admin.modules.system.entity.SysRole;
import com.yix.admin.modules.system.entity.SysUser;
import com.yix.admin.modules.system.entity.dto.SysRoleDto;
import com.yix.admin.modules.system.entity.dto.SysRoleSmallDto;
import com.yix.admin.modules.system.entity.dto.SysUserDto;
import com.yix.admin.modules.system.entity.mapper.SysRoleMapper;
import com.yix.admin.modules.system.entity.mapper.SysRoleSmallMapper;
import com.yix.admin.modules.system.entity.query.SysRoleQuery;
import com.yix.admin.modules.system.repository.SysRoleRepository;
import com.yix.admin.modules.system.repository.SysUserRepository;
import com.yix.admin.modules.system.service.SysRoleService;
import com.yix.common.exception.BadRequestException;
import com.yix.common.exception.EntityExistException;
import com.yix.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/1/28 9:18
 */
@Service
@CacheConfig(cacheNames = "role")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysRoleSmallMapper sysRoleSmallMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private UserCacheClean userCacheClean;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    @Cacheable(key = "'auth:' + #p0.id")
    public List<GrantedAuthority> mapToGrantedAuthorities(SysUserDto user) {
        Set<String> permissions = new HashSet<>();
        // 如果是管理员直接返回
        if (user.getIsAdmin()) {
            permissions.add("admin");
            return permissions.stream().map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }
        Set<SysRole> roles = sysRoleRepository.findByUserId(user.getId());
        permissions = roles.stream().flatMap(role -> role.getMenus().stream())
                .filter(menu -> StringUtils.isNotBlank(menu.getPermission()))
                .map(SysMenu::getPermission).collect(Collectors.toSet());
        return permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public List<SysRoleSmallDto> findByUsersId(String id) {
        return sysRoleSmallMapper.toDto(new ArrayList<>(sysRoleRepository.findByUserId(id)));
    }

    @Override
    public List<SysRole> findInMenuId(List<String> menuIds) {
        return sysRoleRepository.findInMenuId(menuIds);
    }

    @Override
    @Cacheable(key = "'id:' + #p0")
    @Transactional(rollbackFor = Exception.class)
    public SysRoleDto findById(String id) {
        SysRole role = sysRoleRepository.findById(id).orElseGet(SysRole::new);
        ValidationUtil.isNull(role.getId(), "Role", "id", id);
        return sysRoleMapper.toDto(role);
    }

    @Override
    public Integer findByRoles(Set<SysRole> roles) {
        if (roles.size() == 0) {
            return Integer.MAX_VALUE;
        }
        Set<SysRoleDto> roleDtos = new HashSet<>();
        for (SysRole role : roles) {
            roleDtos.add(findById(role.getId()));
        }
        return Collections.min(roleDtos.stream().map(SysRoleDto::getLevel).collect(Collectors.toList()));
    }

    @Override
    public void download(List<SysRoleDto> roles, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysRoleDto role : roles) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("角色名称", role.getName());
            map.put("角色级别", role.getLevel());
            map.put("描述", role.getRemark());
            map.put("创建日期", role.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<SysRoleDto> queryAll(SysRoleQuery criteria) {
        return sysRoleMapper.toDto(sysRoleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public List<SysRoleDto> queryAll() {
        Sort sort = new Sort(Sort.Direction.ASC, "level");
        return sysRoleMapper.toDto(sysRoleRepository.findAll(sort));
    }

    @Override
    public Object queryAll(SysRoleQuery criteria, Pageable pageable) {
        Page<SysRole> page = sysRoleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(sysRoleMapper::toDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(SysRole resources) {
        if (sysRoleRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(SysRole.class, "username", resources.getName());
        }
        resources.setCreaterId(SecurityUtils.getCurrentUserId());
        sysRoleRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRole resources) {
        SysRole role = sysRoleRepository.findById(resources.getId()).orElseGet(SysRole::new);
        ValidationUtil.isNull(role.getId(), "Role", "id", resources.getId());

        SysRole role1 = sysRoleRepository.findByName(resources.getName());

        if (role1 != null && !role1.getId().equals(role.getId())) {
            throw new EntityExistException(SysRole.class, "username", resources.getName());
        }
        role.setName(resources.getName());
        role.setRemark(resources.getRemark());
        role.setDataScope(resources.getDataScope());
        role.setDepts(resources.getDepts());
        role.setLevel(resources.getLevel());
        role.setUpdaterId(SecurityUtils.getCurrentUserId());
        sysRoleRepository.save(role);
        // 更新相关缓存
        delCaches(role.getId(), null);
    }

    @Override
    public void updateMenu(SysRole resources, SysRoleDto roleDTO) {
        SysRole role = sysRoleMapper.toEntity(roleDTO);
        List<SysUser> users = sysUserRepository.findByRoleId(role.getId());
        // 更新菜单
        role.setMenus(resources.getMenus());
        delCaches(resources.getId(), users);
        sysRoleRepository.save(role);
    }

    /**
     * 清理缓存
     * @param id /
     */
    public void delCaches(String id, List<SysUser> users) {
        users = CollectionUtil.isEmpty(users) ? sysUserRepository.findByRoleId(id) : users;
        if (CollectionUtil.isNotEmpty(users)) {
            users.forEach(item -> userCacheClean.cleanUserCache(item.getUsername()));
            Set<String> userIds = users.stream().map(SysUser::getId).collect(Collectors.toSet());
            redisUtils.delByKeys(CacheKey.DATA_USER, userIds);
            redisUtils.delByKeys(CacheKey.MENU_USER, userIds);
            redisUtils.delByKeys(CacheKey.ROLE_AUTH, userIds);
        }
        redisUtils.del(CacheKey.ROLE_ID + id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void untiedMenu(String menuId) {
        // 更新菜单
        sysRoleRepository.untiedMenu(menuId);
    }

    @Override
    public void verification(Set<String> ids) {
        if (sysUserRepository.countByRoles(ids) > 0) {
            throw new BadRequestException("所选角色存在用户关联，请解除关联再试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<String> ids) {
        for (String id : ids) {
            // 更新相关缓存
            delCaches(id, null);
        }
        sysRoleRepository.deleteAllByIdIn(ids);
    }
}
